﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Toxy;

namespace Growatt.CreateCCode
{
    public partial class Form1 : Form
    {

        public Form1(string[] args)
        {
            InitializeComponent();
            this.FormClosed += Form1_FormClosed;
            //if (args.Length == 1 && !string.IsNullOrEmpty(args[0]))
            //{

            //    this.Text = args[0];    
            //    path1 = args[0];
            //    //path2 = args[0];

            //    Debug.WriteLine(path1);
            //    button1_Click(path1, path2);
            //    //Debug.WriteLine("生成成功!");
            //    //Console.ReadLine();
            //    //Environment.Exit(0);
            //}
            //else
            //{
            //    Debug.WriteLine("当前路径输入不合理");
            //    Console.ReadLine();
            //    Environment.Exit(0);
            //}
            if (args.Length==0)
            args = new string[] { "C:\\Users\\Administrator\\Desktop\\12" };
            pathCurrent = args[0];
            button1_Click(Path.Combine(args[0], "CustomCreateModel.xlsx"), path2);

        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }

        static string path1 = string.Empty;
        static string path2 = string.Empty;
        private static string pathCurrent = string.Empty;
        /// <summary>
        /// 生成txt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void button1_Click(string pathFile, string txtpath)
        {
            try
            {
                string Path = pathFile;
                if (!string.IsNullOrEmpty(Path))
                {
          
                    if (!string.IsNullOrEmpty(Path))
                    {
                        List<string> stringBuildersList = new List<string>();
                        List<string> NameList = new List<string>();
                        var lstdb = ReadFromExcelToDatatype(Path, null);
                        var DatatableName = string.Empty;
                        if (lstdb != null && lstdb.Count > 0)
                        {
                            for (int k = 0; k < lstdb.Count; k++)
                            {
                                var datab = lstdb[k];
                                DatatableName += datab.TableName + ",";
                                StringBuilder stringBuilderSingleTable = new StringBuilder();
                                StringBuilder stringBuilderTemp = new StringBuilder();
                                List<string> listSub = null;
                                var strHeard = string.Empty;
                                if (datab != null)
                                {
                                    var dt = datab as DataTable;
                                    DataRow dr = dt.NewRow();
                                    dt.Rows.Add(dr);
                                    if (dt.Rows.Count > 0)
                                    {
                                        for (int i = 1; i < dt.Rows.Count; i++)
                                        {
                                            var row = (DataRow)dt.Rows[i];
                                            var data1 = "";
                                            var data2 = "";
                                            if (i != dt.Rows.Count - 1)
                                            {
                                                if (row[0] != null && row[1] != null && !string.IsNullOrEmpty(row[0].ToString()) && !string.IsNullOrEmpty(row[1].ToString()))
                                                {
                                                    data1 = row[0].ToString();
                                                    data2 = row[1].ToString();
                                                }
                                                else continue;
                                            }

                                            var strHeadtemp = $"const {data1} {data2} = {{";
                                            if (strHeard != strHeadtemp || i == dt.Rows.Count - 1)
                                            {
                                                stringBuilderTemp.Append(strHeard);

                                                if (listSub != null && listSub.Count > 0)
                                                {
                                                    //listSub.Select(o => stringBuilderTemp.AppendLine(o + ",")).ToList();
                                                    listSub.Select(o => stringBuilderTemp.AppendLine(o)).ToList();
                                                    stringBuilderTemp.AppendLine("};");
                                                    stringBuilderSingleTable.AppendLine(stringBuilderTemp.ToString());
                                                    listSub = new List<string>();
                                                    stringBuilderTemp = new StringBuilder();
                                                    if (i == dt.Rows.Count - 1)
                                                    {
                                                        stringBuildersList.Add(stringBuilderSingleTable.ToString());
                                                        NameList.Add(txtpath);
                                                        break;
                                                    }
                                                }
                                                else
                                                {
                                                    listSub = new List<string>();
                                                }
                                                strHeard = strHeadtemp;
                                            }
                                            //获取每一行的参数
                                            string subString = "{";
                                            var lastRemark = "";


                                            txtpath = row.ItemArray[0] as string;
                                            for (int icc = 1; icc < row.ItemArray.Count(); icc++)
                                            {

                                                if (icc > 3 && icc <= row.ItemArray.Count())
                                                {

                                                    var itemString = "";
                                                    if (icc == row.ItemArray.Count() - 1)
                                                    {
                                                        lastRemark = $",\t/*{row.ItemArray[icc]}*/";
                                                    }
                                                    else
                                                    {
                                                        itemString = $"{row.ItemArray[icc]}";
                                                        if (itemString != null)
                                                        {
                                                            subString += itemString.ToString() + "," + "\t";
                                                        }
                                                    }

                                                }

                                            }
                                            subString = DelLastComma(subString);
                                            subString += "}";
                                            subString += lastRemark;
                                            listSub.Add(subString);
                                        }
                                    }
                                }
                            }
                        }
                        NewMethod(NameList, stringBuildersList);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("生成不成功!");
                Environment.Exit(0);
            }
        }
        private static void NewMethod(List<string> txtpaths, List<string> stringBuildersList)
        {
            try
            {
                if (txtpaths.Count == stringBuildersList.Count)
                {
                    for (int i = 0; i < stringBuildersList.Count; i++)
                    {
                        var name = txtpaths[i];
                        var st = stringBuildersList[i];
                        var val = "".TrimEnd();
                        var dataTable = new System.Data.DataTable();
                        dataTable.Columns.Add(new DataColumn());
                        string listStr = st;
                        DataRow dr1 = dataTable.NewRow();
                        dataTable.Rows.Add(dr1);
                        dr1[0] = listStr;
                        if (dataTable != null && !string.IsNullOrEmpty(name))
                        {
                            var result = DataToStringTXT(name, dataTable, val, new List<int>() { dataTable.Columns.Count - 1 }, "Custom" + "_");

                        }
                    }
                    Debug.WriteLine("生成成功!");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("生成失败!");
            }




        }
        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }
        public static List<System.Data.DataTable> ReadFromExcelToDatatype(string FilePath, List<int> listSheet = null)
        {
            List<System.Data.DataTable> dataTables = new List<System.Data.DataTable>();
            try
            {
                // 解析xlsx文档
                ParserContext context = new ParserContext(FilePath);
                ISpreadsheetParser parser = ParserFactory.CreateSpreadsheet(context);
                ToxySpreadsheet ss = parser.Parse();
                if (ss.Tables.Count > 0)
                {
                    listSheet = Enumerable.Range(0, ss.Tables.Count).ToList();
                    for (int s = 0; s < ss.Tables.Count; s++)
                    {
                        if (listSheet != null && listSheet.Contains(s))
                        {
                            var dtToxyTable = ss.Tables[s];
                            var titlename = dtToxyTable.Rows[0].Cells.Select(o => o.Value.ToString()).Distinct().ToList();//不允许出现重名的列

                            var listString = string.Join(",", titlename);

                            Debug.WriteLine(listString);
                            var dtPart = dtToxyTable.ToDataTable();

                            var OriginalCountCol = dtPart.Columns.Count;
                            for (int i = 0; i < OriginalCountCol; i++)
                            {
                                if (i <= titlename.Count - 1)
                                    dtPart.Columns[i].ColumnName = titlename[i].ToString();
                                else
                                    dtPart.Columns.RemoveAt(dtPart.Columns.Count - 1);
                            }
                            if (dtPart.Rows.Count > 0)
                                dtPart.Rows.RemoveAt(0);
                            dataTables.Add(dtPart);
                        }
                        else if (listSheet == null)  //默认全部读取sheet
                        {
                            var dtAll = ss.Tables[s].ToDataTable();

                            dataTables.Add(dtAll);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                Debug.WriteLine("生成不成功!");
                Environment.Exit(0);
            }
            return dataTables;
        }
        public static bool DataToStringTXT(string txtpath, DataTable table, string strHeader, List<int> lstVisibleColumn = null, string fileName = "", bool ShowHeader = false)
        {
            bool result = false;
            try
            {
                string delimiter = ",";
                string path = Path.Combine(pathCurrent, txtpath);
                if (File.Exists(path))
                {
                    var strings = LoadFilelistString(path).ToList();
                    StringBuilder stringBuilder = new StringBuilder();
                    if (strings.Count() > 0)
                    {
                        StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("GB2312"));
                        try
                        {
                            if (ShowHeader)
                                stringBuilder.AppendLine(strHeader);
                            for (int i = 0; i < table.Rows.Count; i++)
                            {
                                string strBufferLine = "";
                                for (int j = 0; j < table.Columns.Count; j++)
                                {
                                    if (lstVisibleColumn != null && lstVisibleColumn.FindAll(o => o.ToString() == j.ToString()) != null)
                                    {
                                        strBufferLine += table.Rows[i][j].ToString() + delimiter;
                                    }
                                    else if (lstVisibleColumn == null)
                                        strBufferLine += table.Rows[i][j].ToString() + delimiter;

                                    if (j == table.Columns.Count - 1 && table.Columns.Count > 0)
                                        strBufferLine = DelLastComma(strBufferLine);
                                }
                                stringBuilder.AppendLine(strBufferLine);
                            }

                            bool isshowFlag = false;
                            for (global::System.Int32 i = 0; i < strings.Count(); i++)
                            {
                                var item = strings[i];
                                sw.WriteLine(item.ToString());
                                if (isshowFlag == false && item.Contains("/*生成代码*/"))
                                {
                                    sw.WriteLine(stringBuilder.ToString());//插入指定内容
                                    isshowFlag = true;
                                }
                            }
                            sw.Close();
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.ToString());
                        }
                        finally
                        {
                            result = true;
                            sw.Close();
                        }
                    }
                }
                else { Debug.WriteLine(".c/.h文件不存在"); }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(".c/.h文件不存在");
                Debug.WriteLine(ex.Message);
            }

            return result;
        }
        public static IEnumerable<string> LoadFilelistString(string FileToRead)
        {
            IEnumerable<string> line = null;
            // Creating enumerable object
            if (File.Exists(FileToRead))
                line = File.ReadLines(FileToRead, Encoding.GetEncoding("GB2312"));
            return line;
        }
    }
}
